#!/bin/sh

# 确保以 root 权限运行
if [ "$(id -u)" -ne 0 ]; then
    echo "请以 root 权限运行此脚本！" >&2
    exit 1
fi

# 定义下载地址和路径
BASE_URL="https://gitee.com/j1111125kk/udpxy-config/raw/master"
CGI_SRC="/tmp/udpxy-config"
HTML_SRC="/tmp/index.html"
CGI_DEST="/www/cgi-bin/udpxy-config"
HTML_DEST="/www/udpxy/index.html"
LIGHTTPD_CONF="/etc/lighttpd/lighttpd.conf"

# 获取本机IP地址（兼容不同系统）
get_ip() {
    IP=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d'/' -f1 | head -1)
    [ -z "$IP" ] && IP=$(ifconfig eth0 2>/dev/null | awk '/inet / {print $2}' | cut -d: -f2)
    [ -z "$IP" ] && IP="192.168.1.1"
    echo "$IP"
}
SERVER_IP=$(get_ip)

# 增强下载函数
download_file() {
    url="$1"
    dest="$2"
    echo "正在下载: $url => $dest"
    
    if command -v curl >/dev/null; then
        curl -k -sSL "$url" -o "$dest" || { echo "下载失败: $url"; exit 1; }
    elif command -v wget >/dev/null; then
        wget --no-check-certificate -q "$url" -O "$dest" || { echo "下载失败: $url"; exit 1; }
    else
        echo "错误：需要 curl 或 wget 来下载文件！" >&2
        exit 1
    fi
}

# 下载必要文件
download_file "$BASE_URL/udpxy-config" "$CGI_SRC"
download_file "$BASE_URL/index.html" "$HTML_SRC"

# 复制文件到目标位置
copy_file() {
    src="$1"
    dest="$2"
    [ ! -f "$src" ] && { echo "错误：源文件 $src 不存在！" >&2; exit 1; }
    mkdir -p "$(dirname "$dest")" || exit 1
    cp -f "$src" "$dest" || { echo "复制失败: $src"; exit 1; }
}
copy_file "$CGI_SRC" "$CGI_DEST"
copy_file "$HTML_SRC" "$HTML_DEST"

# 设置权限
chmod +x "$CGI_DEST" "$HTML_DEST" || { echo "修改权限失败"; exit 1; }

# 处理 lighttpd 配置（修复版）
update_lighttpd() {
    echo "正在更新 lighttpd 配置..."
    if ! grep -q "/cgi-bin/udpxy-config" "$LIGHTTPD_CONF"; then
        # 备份原始配置
        cp "$LIGHTTPD_CONF" "$LIGHTTPD_CONF.bak"
        
        # 使用稳健的 Sed 命令（只处理未注释的配置行）
        sed -i '
        /^[[:space:]]*cgi\.assign[[:space:]]*=/ {
            # 跳过注释行（以#开头）
            /^[[:space:]]*#/! {
                # 处理多行配置块
                :start
                /)[[:space:]]*$/! { N; b start }
                # 替换闭合括号为逗号并追加新条目
                s/)[[:space:]]*$/,/
                a\
    ".sh" => "/bin/sh",\
    ".php" => "/usr/bin/php-cgi",\
    "/cgi-bin/udpxy-config" => ""\
)
            }
        }' "$LIGHTTPD_CONF"
        
        # 验证配置语法
        if lighttpd -t -f "$LIGHTTPD_CONF" >/dev/null 2>&1; then
            echo "配置语法检查通过"
            echo "重启 lighttpd..."
            /etc/init.d/lighttpd restart || { echo "lighttpd 重启失败"; exit 1; }
        else
            echo "错误：lighttpd 配置语法错误，正在回滚修改..."
            cp "$LIGHTTPD_CONF.bak" "$LIGHTTPD_CONF"
            exit 1
        fi
    else
        echo "配置已存在，无需修改"
    fi
}
update_lighttpd

# 获取udpxy端口（从UCI配置）
get_udpxy_port() {
    UCI_CONFIG="/etc/config/udpxy"
    [ ! -f "$UCI_CONFIG" ] && { echo "错误：未找到UCI配置文件"; exit 1; }
    PORT=$(awk '/config udpxy/{cfg=1} cfg && /option port/{gsub(/'\''|"/,"",$3); print $3; exit}' "$UCI_CONFIG")
    [ -z "$PORT" ] && PORT=4022
    echo "$PORT"
}
PORT=$(get_udpxy_port)

# 输出访问信息
echo "-------------------------------------"
echo "安装完成！访问地址:"
echo "管理页面: http://${SERVER_IP}/udpxy"
echo "状态页面: http://${SERVER_IP}:${PORT}/status"